package com.nakamachizu.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Logger;

import org.mobylet.core.Carrier;
import org.mobylet.core.Mobylet;
import org.mobylet.core.MobyletFactory;
import org.mobylet.core.device.Device;
import org.mobylet.core.device.DeviceDisplay;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.StringUtil;
import org.slim3.util.TimeZoneLocator;

import com.google.appengine.api.datastore.GeoPt;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.nakamachizu.collection.ApiKeyMap;
import com.nakamachizu.collection.IconNameMap;
import com.nakamachizu.constant.AppConstant;
import com.nakamachizu.constant.SessionKeyConstant;
import com.nakamachizu.model.LandMarkData;
import com.nakamachizu.model.MapData;
import com.nakamachizu.model.MemberData;
import com.nakamachizu.service.MapDataService;
import com.nakamachizu.util.ErrorsUtil;
import com.nakamachizu.util.ForwardUtil;

public class ViewController extends Controller {

    private static final Logger log = Logger.getLogger(ViewController.class.getName());
    
    protected List<String> messages = new ArrayList<String>();
    private String zoomLevel;
    private String centerLat;
    private String centerLng;
    private String r;
    private String l;
    private String u;
    private String d;
    private Calendar now;
    
    @Override
    public Navigation run() {
        
        UserService userService = UserServiceFactory.getUserService();        
        User user = userService.getCurrentUser();
        String logoutUrl = userService.createLogoutURL("/");
        
        if(user == null){
            return redirect(userService.createLoginURL(request.getRequestURI()));
        }
        MapDataService mds = new MapDataService();
        MapData map = mds.getMapData(user.getEmail());
        if(map == null){
            return redirect("/make");
        }
        
        init();
        
        Integer w = 600;
        Integer h = 370;
        
        Mobylet mobylet = MobyletFactory.getInstance();
        Carrier carrier = mobylet.getCarrier();
        if(!carrier.equals(Carrier.OTHER)){
            DeviceDisplay display = mobylet.getDisplay();
            Device device = mobylet.getDevice();

            w = display.getWidth();  //ブラウザ幅
            h = display.getHeight(); //ブラウザ高さ
            if(w == null || w.intValue() <= 0){
                w = 100;
            }
            if(h == null || h.intValue() <= 0){
                h = 100;
            }
            h = (int)(h * 0.7);
            
            List<MemberData> memList = map.getMemberDataListRef().getModelList();
            List<LandMarkData> landList = map.getLandMarkDataListRef().getModelList();

            if(StringUtil.isEmpty(centerLat) || StringUtil.isEmpty(centerLng)){
                if(landList != null && landList.size() > 0){
                    centerLat = Float.toString(landList.get(0).getLatLng().getLatitude());
                    centerLng = Float.toString(landList.get(0).getLatLng().getLongitude());
                }else if(memList != null && memList.size() > 0){
                    centerLat = Float.toString(memList.get(0).getLatLng().getLatitude());
                    centerLng = Float.toString(memList.get(0).getLatLng().getLongitude());
                }else{
                    centerLat = "35.6810976";
                    centerLng = "139.7671169";
                }
            }
            requestScope("landMarkList", landList);
            requestScope("memberList", memList);
        }
        
        if(!StringUtil.isEmpty(centerLat) && !StringUtil.isEmpty(centerLng)){
            GeoPt center = mds.getCenter(centerLat, centerLng, Float.parseFloat(r), Float.parseFloat(l), Float.parseFloat(u), Float.parseFloat(d));
            requestScope("cLat", center.getLatitude());
            requestScope("cLng", center.getLongitude());
        }else{
            requestScope("cLat", 35.68076);
            requestScope("cLng", 139.767294);
        }

        requestScope("angle", mds.getAngle(zoomLevel, w));
        requestScope("zoom", zoomLevel);
        requestScope("messages", messages);
        requestScope("now", now.getTime().getTime());
        requestScope("logoutUrl", logoutUrl);
        requestScope("serverName", request.getServerName());
        requestScope("apiKey", ApiKeyMap.API_KEY_MAP.get(request.getServerName()));
        requestScope("width", w);
        requestScope("height", h);
        requestScope("iconNameMap", IconNameMap.ICON_NAME);
        requestScope("expire", map.getExpire());
        requestScope("mapKey", map.getAccessKey());
        requestScope("viewPassword", map.getViewPassword());
        requestScope("title", map.getTitle());
        sessionScope(SessionKeyConstant.MAP_DATA_SESSION_KEY(), mds.createMapDataSession(map));
        
        
        return forward(ForwardUtil.forwardJsp("view.jsp"));
    }
    
    protected void init(){
        now = Calendar.getInstance(TimeZoneLocator.get());
        zoomLevel = requestScope("zoom");
        if(StringUtil.isEmpty(zoomLevel)){
            zoomLevel = AppConstant.DEFAULT_ZOOM_LEVEL();
        }
        centerLat = requestScope("cLat");
        centerLng = requestScope("cLng");
        r = requestScope("r");
        l = requestScope("l");
        u = requestScope("u");
        d = requestScope("d");
        
        if(StringUtil.isEmpty(r)){
            r = "0";
        }
        if(StringUtil.isEmpty(l)){
            l = "0";
        }
        if(StringUtil.isEmpty(u)){
            u = "0";
        }
        if(StringUtil.isEmpty(d)){
            d = "0";
        }
    }
    
    @Override
    protected Navigation handleError(Throwable error) {
        error.printStackTrace();
        log.severe(ErrorsUtil.stackTrace(error));
        return forward("error.jsp");
    }
}
